package zhihuilan.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import zhihuilan.common.utils.ToolsUtils;
import zhihuilan.dto.MyCircleDto;
import zhihuilan.dto.WxMiniPageDto;
import zhihuilan.entity.*;
import zhihuilan.mapper.*;
import zhihuilan.params.query.MyAcquisitionQueryParam;
import zhihuilan.params.query.MyCircleQueryParam;
import zhihuilan.params.save.MyCircleSaveParam;
import zhihuilan.service.MyCircleService;
import zhihuilan.service.MySearchService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户数据 服务实现
 *
 * @author ruoyi
 */
@Service
public class MyCircleServiceImpl extends ServiceImpl<MyCircleMapper, MyCircle> implements MyCircleService {

    private final static String tbName = "circle";

    @Resource
    private MySearchService mySearchService;

    @Resource
    private MyCircleThumbupMapper myCircleThumbupMapper;

    @Resource
    private MyCircleDiscussMapper myCircleDiscussMapper;

    @Resource
    private MyCircleDiscussThumbupMapper myCircleDiscussThumbupMapper;

    @Resource
    private MyCircleCollectionMapper myCircleCollectionMapper;


    @Override
    public Page<MyCircle> selectPageList(MyCircleQueryParam queryParam) {
        QueryWrapper<MyCircle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        if (ObjectUtils.isEmpty(queryParam)) {
            return null;
        }
        if (!ObjectUtils.isEmpty(queryParam.getStaffId())) {
            queryWrapper.eq("staff_id", queryParam.getStaffId());
        }
        if (!ObjectUtils.isEmpty(queryParam.getUtype()) && queryParam.getUtype().equals(1)){
            if (!ObjectUtils.isEmpty(queryParam.getShareVideoId())&&queryParam.getShareVideoId()>0) {
                queryWrapper.ne("id", queryParam.getShareVideoId());
            }
            queryWrapper.eq("utype", 1);
        }
        else {
            queryWrapper.ne("utype", 1);
        }
        if (!ObjectUtils.isEmpty(queryParam.getType())) {
            queryWrapper.eq("type", queryParam.getType());
        }
//        System.out.println(queryParam.getDistrictid().length());
//        System.out.println(queryParam);
        if (!ObjectUtils.isEmpty(queryParam.getDistrictid())) {
            if (queryParam.getDistrictid().length() >= 6) {
                queryWrapper.eq("districtid", queryParam.getDistrictid());
            } else if (queryParam.getDistrictid().length() == 4) {
                queryWrapper.eq("districtid1", queryParam.getDistrictid());
            } else if (queryParam.getDistrictid().length() == 2) {
                queryWrapper.eq("districtid2", queryParam.getDistrictid());
            }
        }
        if (!ObjectUtils.isEmpty(queryParam.getRand())) {
            queryWrapper.orderByDesc("rand(" + queryParam.getRand() + ")");
        } else {
            queryWrapper.orderByDesc("create_time");
        }
        long pageNum = 0;
        long pageSize = 10;
        if (queryParam.getPage() >= 0L) {
            pageNum = queryParam.getPage();
        }
        if (queryParam.getPageSize() > 0L) {
            pageSize = queryParam.getPageSize();
        }
        Page<MyCircle> page = new Page<>(pageNum, pageSize);
        this.baseMapper.selectPage(page, queryWrapper);
        return page;
    }

    @Override
    public Long selectCount(MyCircleQueryParam queryParam) {
        QueryWrapper<MyCircle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        if (!ObjectUtils.isEmpty(queryParam)) {
            if (!ObjectUtils.isEmpty(queryParam.getStaffId())) {
                queryWrapper.eq("staff_id", queryParam.getStaffId());
            }
            if (!ObjectUtils.isEmpty(queryParam.getUtype())) {
                queryWrapper.ne("utype", queryParam.getUtype());
            }
        }
        Long count = this.baseMapper.selectCount(queryWrapper);
        return count;
    }

    @Override
    public MyCircle selectById(Integer id) {
        return this.baseMapper.selectById(id);
    }

    @Override
    public MyCircle selectOne(Integer staffId) {
        if (ObjectUtils.isEmpty(staffId)) {
            return null;
        }
        QueryWrapper<MyCircle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.eq("staff_id", staffId);
        queryWrapper.ne("type", 3);
        queryWrapper.last("limit 1");
        return this.baseMapper.selectOne(queryWrapper);
    }
    @Override
    public MyCircle selectOneByStaffId(Integer staffId) {
        if (ObjectUtils.isEmpty(staffId)) {
            return null;
        }
        QueryWrapper<MyCircle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 1);
        queryWrapper.eq("staff_id", staffId);
            queryWrapper.ne("utype", 1);
            queryWrapper.orderByDesc("id");
            queryWrapper.last("limit 1");
        return this.baseMapper.selectOne(queryWrapper);
    }


    @Transactional
    @Override
    public MyCircle addEntity(MyCircle saveEntity) {
        try {
            if (ObjectUtils.isEmpty(saveEntity.getId())) {
                this.baseMapper.insert(saveEntity);
            } else {
                return null;
            }
            return saveEntity;
        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public MyCircle addEntityAndSearch(MyCircle saveEntity) {
        try {
            if (ObjectUtils.isEmpty(saveEntity.getId())) {
                this.baseMapper.insert(saveEntity);
            } else {
                return null;
            }
            this.updateMySearchInfo(saveEntity, 1);
            return saveEntity;
        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Override
    public MyCircle updateEntity(MyCircle saveEntity) {
        try {
            if (!ObjectUtils.isEmpty(saveEntity.getId())) {
                this.baseMapper.updateById(saveEntity);
            } else {
                return null;
            }
            return saveEntity;
        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public MyCircle updateEntityAndSearch(MyCircle saveEntity) {
        try {
            if (!ObjectUtils.isEmpty(saveEntity.getId())) {
                this.baseMapper.updateById(saveEntity);
            } else {
                return null;
            }
            this.updateMySearchInfo(saveEntity, 2);
            return saveEntity;
        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public Boolean deleteById(Integer id) {
        try {
            MyCircle myCircle = this.selectById(id);
            if (!ObjectUtils.isEmpty(myCircle)) {
                this.baseMapper.deleteById(id);
            } else {
                return false;
            }
            return true;
        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Transactional
    @Override
    public Boolean deleteByIdAndSearch(Integer id) {
        try {
            MyCircle myCircle = this.selectById(id);
            if (ObjectUtils.isEmpty(myCircle)) {
                return false;
            }
            myCircle.setStatus(0);
            this.baseMapper.updateById(myCircle);
            QueryWrapper<MyCircleThumbup> thumbupQueryWrapper = new QueryWrapper<>();
            thumbupQueryWrapper.eq("pid", id);
            this.myCircleThumbupMapper.delete(thumbupQueryWrapper);
            QueryWrapper<MyCircleDiscuss> discussQueryWrapper = new QueryWrapper<>();
            discussQueryWrapper.eq("pid", id);
            this.myCircleDiscussMapper.delete(discussQueryWrapper);
            QueryWrapper<MyCircleDiscussThumbup> discussThumbupQueryWrapper = new QueryWrapper<>();
            discussThumbupQueryWrapper.eq("pid", id);
            this.myCircleDiscussThumbupMapper.delete(discussThumbupQueryWrapper);
            QueryWrapper<MyCircleCollection> collectionQueryWrapper = new QueryWrapper<>();
            collectionQueryWrapper.eq("pid", id);
            this.myCircleCollectionMapper.delete(collectionQueryWrapper);
            Boolean result = this.updateMySearchInfo(myCircle, 3);
            return result;
        } catch (RuntimeException e) {
            throw new RuntimeException("操作失败：" + e.getMessage());
        }
    }

    @Override
    public Boolean addShareCount(Integer id) {
        if (ObjectUtils.isEmpty(id))
            return false;
        MyCircle myCircle = this.selectById(id);
        if (ObjectUtils.isEmpty(myCircle)) {
            return false;
        }
        Integer shareCount = 0;
        if(myCircle.getShare()!=null){
            shareCount = myCircle.getShare();
        }
        myCircle.setShare(shareCount + 1);
        this.baseMapper.updateById(myCircle);
        return true;
    }

    @Override
    public Long getTodaySendCount(MyCircleQueryParam queryParam) {
        QueryWrapper<MyCircle> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("staff_id", queryParam.getStaffId());
        queryWrapper.gt("create_time", queryParam.getCreateTime());
        if (!ObjectUtils.isEmpty(queryParam.getType()))
            queryWrapper.eq("type", queryParam.getType());
        if (!ObjectUtils.isEmpty(queryParam.getBuy()))
            queryWrapper.eq("buy", queryParam.getBuy());
        return this.baseMapper.selectCount(queryWrapper);
    }

    /**
     * 新增、更新、删除查询表相关信息；
     *
     * @param myCircle 线缆圈信息
     * @param type     操作类型：1、新增；2、更新；3、删除；
     * @return 返回操作成功或者失败！
     * @author chenk
     * @date 2025年3月4日 15:50:33
     */
    private Boolean updateMySearchInfo(MyCircle myCircle, Integer type) {
        if (type.equals(3)) {
            this.mySearchService.deleteByTableAndId(tbName, myCircle.getId());
            return true;
        }

        MySearch mySearch = new MySearch();
        mySearch.setStaffId(myCircle.getStaffId());
        String title = ToolsUtils.replaceCharToSearch(myCircle.getTitle());
        String content = ToolsUtils.replaceCharToSearch(myCircle.getContent());
        mySearch.setName(title);
        mySearch.setContent(content);
        mySearch.setImg(myCircle.getImage());
        mySearch.setVideo(myCircle.getVideo());
        mySearch.setLogo(myCircle.getLogo());
        mySearch.setTbName(tbName);
        mySearch.setPid(myCircle.getId());
        mySearch.setType(0);
        mySearch.setUtype(myCircle.getUtype());
        mySearch.setLng(myCircle.getLng());
        mySearch.setLat(myCircle.getLat());
        mySearch.setRegion(myCircle.getRegion());
        mySearch.setLnggd(myCircle.getLnggd());
        mySearch.setLatgd(myCircle.getLatgd());
        mySearch.setDistrictid(myCircle.getDistrictid());
        mySearch.setDistrictid1(myCircle.getDistrictid1());
        mySearch.setDistrictid2(myCircle.getDistrictid2());
        mySearch.setAddress(!ObjectUtils.isEmpty(myCircle.getAddress()) ? myCircle.getAddress() : myCircle.getRegion());
        mySearch.setCreateTime(Integer.parseInt(new Date().getTime() / 1000 + ""));
        mySearch.setCreateUser(myCircle.getCreateUser());
        if (type.equals(1)) {
            this.mySearchService.addEntity(mySearch);
        }
        if (type.equals(2)) {
            this.mySearchService.updateEntity(mySearch);
        }
        return true;
    }

    @Override
    public WxMiniPageDto<MyCircleDto> selectStaffToCirclePageList(MyCircleQueryParam queryParam) {

        long pageNum = 0;
        long pageSize = 10;
        if (queryParam.getPage() >= 1L) {
            pageNum = queryParam.getPage();
        }
        if (queryParam.getPageSize() > 0L) {
            pageSize = queryParam.getPageSize();
        }
        if (pageNum > 0) {
            pageNum = pageSize * (pageNum - 1);
        }
        if (!ObjectUtils.isEmpty(queryParam.getDistrictid())) {
        } else {
            if (!ObjectUtils.isEmpty(queryParam.getProvinceid())) {
                queryParam.setDistrictid(queryParam.getProvinceid());
            }
        }

        List<MyCircleDto> selectList = this.baseMapper.selectListPageToStaff(pageNum, pageSize, queryParam.getUtype(), queryParam.getStaffId(), queryParam.getDistrictid(), queryParam.getRand());
        Long count = this.baseMapper.selectListCountToStaff(queryParam.getUtype(), queryParam.getStaffId(), queryParam.getDistrictid());
        WxMiniPageDto<MyCircleDto> result = new WxMiniPageDto(pageNum, pageSize);
//        List<MyCircleDto> convertList = selectList.stream().map(po -> {
//            QueryWrapper<MyFactoryFav> queryWrapperFav = new QueryWrapper<>();
//            queryWrapperFav.eq("staffid", queryParam.getStaffId());
//            queryWrapperFav.eq("fav_staffid", po.getStaffId());
//            Long favCount = this.myFactoryFavMapper.selectCount(queryWrapperFav);
//            if (ObjectUtils.isEmpty(favCount) || favCount == 0L) {
//                po.setIsfav(0);
//            } else {
//                po.setIsfav(1);
//            }
////            po.setVideo(StringEscapeUtils.unescapeHtml4(po.getVideo()));
//            po.setContent(StringEscapeUtils.unescapeHtml4(po.getContent()));
//            return po;
//        }).collect(Collectors.toList());
        result.setData(selectList);
        result.setTotal(count);
        return result;
    }
}
